package com.shanzhu.beadhouse.common.config.security.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.shanzhu.beadhouse.common.config.security.entity.LoginUserDetails;
import com.shanzhu.beadhouse.common.constant.ExceptionEnum;
import com.shanzhu.beadhouse.common.constant.RedisConstant;
import com.shanzhu.beadhouse.common.util.AssertUtil;
import com.shanzhu.beadhouse.dao.mapper.AuthMapper;
import com.shanzhu.beadhouse.entity.po.Auth;
import com.shanzhu.beadhouse.entity.po.Staff;
import com.shanzhu.beadhouse.entity.vo.LoginUserVo;
import com.shanzhu.beadhouse.service.common.StaffFunc;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 自定义数据库查询
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private StaffFunc staffFunc;
    @Resource
    private AuthMapper authMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询基本信息
        Staff staff = staffFunc.getStaffByAccount(username);
        // 未查询到数据
        AssertUtil.notNull(staff, ExceptionEnum.CERTIFICATION_ERROR);
        // 查询权限信息
        String roleIdStr = staff.getRoleId().toString();
        String idStr = stringRedisTemplate.opsForValue().get(RedisConstant.PREFIX_AUTH_ID+roleIdStr);
        String urlStr = stringRedisTemplate.opsForValue().get(RedisConstant.PREFIX_AUTH_URL+roleIdStr);
        List<Long> authIdList;
        List<String> authUrlList;
        if (idStr==null||idStr.isEmpty()||urlStr==null||urlStr.isEmpty()){
            System.out.println("未命中");
            String uuid = java.util.UUID.randomUUID().toString();//唯一标识
            Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent(RedisConstant.PREFIX_AUTH_LOCK+roleIdStr,uuid,10, TimeUnit.SECONDS);
            if (lock){
                try {
                    authIdList = new ArrayList<>();
                    authUrlList = new ArrayList<>();

                    for (Auth auth : authMapper.listAuthByRoleId(staff.getRoleId())) {
                        authIdList.add(auth.getId());
                        authUrlList.add(auth.getUrl());
                    }
                    stringRedisTemplate.opsForValue().set(RedisConstant.PREFIX_AUTH_ID+roleIdStr, JSONUtil.toJsonStr(authIdList));
                    stringRedisTemplate.opsForValue().set(RedisConstant.PREFIX_AUTH_URL+roleIdStr, JSONUtil.toJsonStr(authUrlList));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    // 使用Lua脚本确保只有锁的持有者才能删除锁
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then " +
                            "return redis.call('del', KEYS[1]) " +
                            "else " +
                            "return 0 " +
                            "end";

                    stringRedisTemplate.execute(
                            new DefaultRedisScript<>(script, Long.class),
                            Collections.singletonList(RedisConstant.PREFIX_AUTH_LOCK+roleIdStr),
                            uuid
                    );
                }
            }else {
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return loadUserByUsername(username);
            }
        }else {
            System.out.println("命中");
            authIdList=JSONUtil.toList(idStr, Long.class);
            authUrlList=JSONUtil.toList(urlStr, String.class);
        }

        // 把数据封装成UserDetails返回
        LoginUserVo loginUserVo = BeanUtil.toBean(staff, LoginUserVo.class);
        loginUserVo.setAuthIdList(authIdList);
        loginUserVo.setAuthUrlList(authUrlList);
        return new LoginUserDetails(loginUserVo);
    }
}
